import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getUserInfo } from '@/api/user'
import { addDynamicsRouter } from '@/utils/permission'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login/index.vue'),
      meta: {
        isStatic: true
      }
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('@/views/Layout/index.vue'),
      meta: {
        isStatic: true
      }
      // children: [
      //   {
      //     path: 'user/list',
      //     component: () => import('../views/User/index.vue')
      //   },
      //   {
      //     path: 'swiper/list',
      //     component: () => import('../views/Swiper/index.vue')
      //   },
      //   {
      //     path: 'goods/list',
      //     component: () => import('../views/Goods/index.vue')
      //   },
      //   {
      //     path: 'echarts/show',
      //     component: () => import('../views/Visible/echarts.vue')
      //   },
      //   {
      //     path: 'echarts/other',
      //     component: () => import('../views/Visible/echarts-other.vue')
      //   },
      //   {
      //     path: 'editor/submit',
      //     component: () => import('../views/Editor/index.vue')
      //   },
      //   {
      //     path: 'map/baidu',
      //     component: () => import('../views/Map/baidu.vue')
      //   },
      //   {
      //     path: 'map/baidu-vue3',
      //     component: () => import('../views/Map/baidu-vue3.vue')
      //   }
      // ]
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('../views/NotFound/index.vue'),
      meta: {
        isStatic: true
      }
    }
  ]
})

const whiteList = ['/login']
//加载一次权限的数据的标识   可以算是一种优化
export const operator = {
  isInit: true
}
//全局前置守卫
router.beforeEach(async (to, from) => {
  const store = useUserStore()
  if (whiteList.includes(to.path)) {
    return true
  } else {
    if (store.userInfo?.token) {
      //第一次进入到导航守卫的时候，去加载一次权限的数据，后续就无需重复加载了
      if (operator.isInit) {
        // 获取用户信息（包含的有用户的权限）
        const res = await getUserInfo()
        // 把用户信息保存到仓库中
        store.setUserInfo({ token: store.userInfo.token, ...res.data.data })
        //根据权限列表，动态添加路由
        addDynamicsRouter(res.data.data.menus)
        //vue3要调用router中的replace方法才能在刷新浏览器是起作用
        //vue2要调用一次next方法
        router.replace({ path: to.path })

        operator.isInit = false
      }
      return true
    } else {
      return { name: 'login', query: { redirect: to.fullPath } }
    }
  }
})

export default router
